package com.jiecao.news.jiecaonews.activity;

import java.util.ArrayList;
import java.util.Date;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jiecao.news.jiecaonews.BaseActivity;
import com.jiecao.news.jiecaonews.R;
import com.jiecao.news.jiecaonews.adapters.NewsAdapter;
import com.jiecao.news.jiecaonews.backgroung.FlushTask;
import com.jiecao.news.jiecaonews.backgroung.GetListDataTask;
import com.jiecao.news.jiecaonews.backgroung.GetMoreDataTask;
import com.jiecao.news.jiecaonews.backgroung.UpdateInfoTask;
import com.jiecao.news.jiecaonews.dao.NewsDao;
import com.jiecao.news.jiecaonews.pojo.NewsListItem;
import com.jiecao.news.jiecaonews.util.DensityUtil;
import com.jiecao.news.jiecaonews.util.NetUtil;
import com.jiecao.news.jiecaonews.util.SharedPreferencesUtil;
import com.jiecao.news.jiecaonews.util.UtilsClass;
import com.jiecao.news.jiecaonews.util.cache.ImageLoader;
import com.jiecao.news.jiecaonews.util.constants.Constants;
import com.jiecao.news.jiecaonews.util.umeng.ShareUtils;
import com.jiecao.news.jiecaonews.util.view.PullToRefreshBase.OnRefreshListener;
import com.jiecao.news.jiecaonews.util.view.PullToRefreshListView;
import com.jiecao.news.jiecaonews.util.view.SlideIt;
import com.umeng.analytics.MobclickAgent;
import com.umeng.newxp.common.ExchangeConstants;
import com.umeng.newxp.controller.ExchangeDataService;
import com.umeng.newxp.view.ExchangeViewManager;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;

/**
 * 新闻页
 * 
 * @author lidongwei
 * 
 */
public class NewsActivity extends BaseActivity {
	protected static final String TAG = "NewsActivity";
	// bannner
	private ArrayList<NewsListItem> mItems;// 新闻条目数据list
	private NewsAdapter newsAdapter;// 新闻条目list adapter
	private PullToRefreshListView mPullRefreshListView;// 下拉刷新view
	private View mloadMoreView; // 加载更多view
	private TextView mloadMoreText; // 加载更多view中的按钮
	private ProgressBar mloadMoreProgressBar;// 加载更多中的progressbar
	private int mvisibleLastIndex = 0; // 最后的可视项索引
	private ListView actualListView;// 下拉刷新list中的listview
	private ImageLoader mImageLoader;// 数据加载
	private ImageView showButton;
	private FrameLayout newsContentFl;
	private ImageView shareSina;
	private ImageView shareTencent;
	private ImageView shareFriends;
	private ImageView info;
	private TextView newsDateWeatherHeadText;//普通日期
	private TextView newsLunarHeadText;//农历日期
	private ImageView moreApp;
	
	

	private long lastClickTime = 0;
	private long dy;

	// 数据库操作
	private NewsDao newsDao;
	private long lastBackTime;

	private SlideIt slideIt;
	private UMSocialService controller;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_news);
		registerReceiver(finishbr, new IntentFilter(finish_br_name));
		
		
		newsDao = new NewsDao(this);
		shareSina = (ImageView) findViewById(R.id.share_sina);
		shareTencent = (ImageView) findViewById(R.id.share_tencent);
		shareFriends = (ImageView)findViewById(R.id.share_friends);
		info = (ImageView) findViewById(R.id.info);
		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
		showButton = (ImageView) findViewById(R.id.show_button);
		newsContentFl = (FrameLayout) findViewById(R.id.news_content_fl);
		newsDateWeatherHeadText = (TextView)findViewById(R.id.news_date_weather_head_text);
		newsLunarHeadText  = (TextView)findViewById(R.id.news_lunar_head_text);
		moreApp = (ImageView)findViewById(R.id.banner_more_app);
		
		newsDateWeatherHeadText.setText(UtilsClass.getNowDate());
		newsLunarHeadText.setText(UtilsClass.getLunar());
		
		/**
		 * 分享相关 start
		 */
		dy = DensityUtil.dip2px(getApplicationContext(), 74);//滑动的距离：74dp
		//友盟组件
		com.umeng.socom.Log.LOG = true;
		controller = UMServiceFactory.getUMSocialService(NewsActivity.class.getName(),
				RequestType.SOCIAL);
		 UMImage mUMImgBitmap = new UMImage(this,BitmapFactory.decodeResource(getResources(), R.drawable.share_pic));
		ShareUtils.initshare(this, mUMImgBitmap, getString(R.string.download_url),  controller,getString(R.string.share_title));
		controller.setShareContent(getString(R.string.share_content));
		shareSina.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
//				if (System.currentTimeMillis() - lastClickTime > 400) {
//					controller.directShare(NewsActivity.this, SHARE_MEDIA.SINA,
//							null);
//				}
//				lastClickTime = System.currentTimeMillis();
				// 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口
				controller.postShare(NewsActivity.this,SHARE_MEDIA.SINA, 
				        new SnsPostListener() {
				                @Override
				                public void onStart() {
//				                    Toast.makeText(NewsActivity.this, "开始分享.", Toast.LENGTH_SHORT).show();
				                }

				                @Override
				                public void onComplete(SHARE_MEDIA platform, int eCode,SocializeEntity entity) {
				                     if (eCode == 200) {
//				                         Toast.makeText(NewsActivity.this, "分享成功.", Toast.LENGTH_SHORT).show();
				                     } else {
				                          String eMsg = "";
				                          if (eCode == -101){
				                              eMsg = "没有授权";
				                          }
//				                          Toast.makeText(NewsActivity.this, "分享失败[" + eCode + "] " + 
//				                                             eMsg,Toast.LENGTH_SHORT).show();
				                     }
				              }
				});
			}
			
		});
		
		shareTencent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				controller.directShare(NewsActivity.this, SHARE_MEDIA.WEIXIN, null);
			}
		});
		
		shareFriends.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
					controller.directShare(NewsActivity.this, SHARE_MEDIA.WEIXIN_CIRCLE, null);
			}
		});
		
		info.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setClass(NewsActivity.this, AboutActivity.class);
				startActivity(i);
			}
		});
		
		slideIt = new SlideIt(newsContentFl);
		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				refreshNewsList();
			}

		});
		showButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (System.currentTimeMillis() - lastClickTime > 500) {
						slideIt.slideview(0, dy, 400, 0,showButton);
				}
				lastClickTime = System.currentTimeMillis();
			}
		});
		moreApp.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ExchangeDataService service = new ExchangeDataService();
		        new ExchangeViewManager(NewsActivity.this,service)
		                    .addView(ExchangeConstants.type_list_curtain, null);     
				
			}
		});
		actualListView = mPullRefreshListView.getRefreshableView();
		actualListView.setOnItemClickListener(actualListItemClickListener);
		mItems = newsDao.getNewsList();
		mloadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);
		mloadMoreText = (TextView) mloadMoreView
				.findViewById(R.id.loadMoreButton);
		mloadMoreProgressBar = (ProgressBar) mloadMoreView
				.findViewById(R.id.load_more_progressBar);
		actualListView.setOnScrollListener(onScrollListener);

		actualListView.addFooterView(mloadMoreView); // 设置列表底部视图
		mImageLoader = ImageLoader.getInstance(this);
		newsAdapter = new NewsAdapter(getLayoutInflater(), mItems, mImageLoader);
		actualListView.setAdapter(newsAdapter);
		//获取更新信息
		new UpdateInfoTask(this).execute();
		// 模拟下拉刷新
		mPullRefreshListView.setRefreshing();
		refreshNewsList();
	}

	OnScrollListener onScrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				mImageLoader.lock();
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				mImageLoader.unlock();
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				mImageLoader.lock();
				break;
			default:
				break;
			}

			int itemsLastIndex = newsAdapter.getCount() - 1; // 数据集最后一项的索引
			int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
					&& mvisibleLastIndex == lastIndex) {
				mloadMoreText.setVisibility(View.VISIBLE);
				mloadMoreProgressBar.setVisibility(View.VISIBLE);
				mloadMoreText.setText(getResources().getString(
						R.string.pull_up_to_refreshing_label)); // 设置按钮文字loading
				String time = (null == mItems || mItems.size() <= 0) ? null
						: mItems.get(mItems.size() - 1).getPublishTime();
				if(!NetUtil.isNetworkConnected(NewsActivity.this)){
					Toast.makeText(NewsActivity.this, "您的网络出现问题", Toast.LENGTH_SHORT).show();
				}
				new GetMoreDataTask(mItems, newsAdapter, mloadMoreText,
						mloadMoreProgressBar, time).execute();
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			mvisibleLastIndex = firstVisibleItem + visibleItemCount - 1;
		}
	};

	/**
	 * 新闻列表单一item点击事件
	 */

	private OnItemClickListener actualListItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View arg1, int pos,
				long id) {
			NewsListItem newsListItem = (NewsListItem) parent
					.getItemAtPosition(pos);
			if(newsListItem==null){
				Log.e(TAG,"点击处未获取到item");
				return;
			}
			Intent intent = new Intent();
			intent.putExtra("id", newsListItem.getId());
			intent.putExtra("title", newsListItem.getTitle());
			intent.putExtra("icon", newsListItem.getIcon());
			intent.putExtra("intro", newsListItem.getIntro());
			intent.setClass(NewsActivity.this, NewsInfoActivity.class);
			startActivity(intent);

		}

	};

	private void refreshNewsList() {
		if(!NetUtil.isNetworkConnected(this)){
			Toast.makeText(this, "您的网络出现问题", Toast.LENGTH_SHORT).show();
			mPullRefreshListView.onRefreshComplete();
			return;
		}
		new  FlushTask(Constants.NEED_FLUSH_URL,SharedPreferencesUtil.readFlushDate(this),this).execute();
		String time = (null == mItems || mItems.size() <= 0) ? null : mItems
				.get(0).getPublishTime();
		String isAfter = (null == mItems || mItems.size() <= 0) ? Constants.NEWS_LIST_NOT_AFTER
				: Constants.NEWS_LIST_IS_AFTER;
		//改造成一次性加载20条的，每次都刷都刷新
		time ="1970-01-01 08:00:00";
		isAfter =Constants.NEWS_LIST_IS_AFTER;
		new GetListDataTask(mItems, newsAdapter, mPullRefreshListView,
				 time, isAfter, getApplication()).execute();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			// 二级页面不是webview，我们可以再点一次退出
			long now = new Date().getTime();
			if (now - lastBackTime < Constants.TIME_DIFF) {
				Intent i = new Intent(finish_br_name);
				sendBroadcast(i);
			} else {
				lastBackTime = now;
				Toast.makeText(this, "再点一次将退出", Constants.TIME_DIFF).show();
			}
			return true;

		}
		return super.onKeyDown(keyCode, event);
	}

//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		super.onActivityResult(requestCode, resultCode, data);
//		/**
//		 * 使用SSO必须添加，指定获取授权信息的回调页面，并传给SDK进行处理
//		 */
//		UMSsoHandler sinaSsoHandler = controller.getConfig()
//				.getSinaSsoHandler();
//		if (sinaSsoHandler != null
//				&& requestCode == UMSsoHandler.DEFAULT_AUTH_ACTIVITY_CODE) {
//			sinaSsoHandler.authorizeCallBack(requestCode, resultCode, data);
//		}
//	}
	
	@Override 
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    /**使用SSO授权必须添加如下代码 */
	    UMSsoHandler ssoHandler = controller.getConfig().getSsoHandler(requestCode) ;
	    if(ssoHandler != null){
	       ssoHandler.authorizeCallBack(requestCode, resultCode, data);
	    }
	}
	
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
}
